package com.navi.alarm.service;

import com.navi.alarm.tx.amstx.AmsTxI;
import com.navi.alarm.tx.amstx.AmsTxO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

/**
 * Created by lin.xin on 2018/2/11.
 */
@Service
@Slf4j
public class SendMailService {

    @Value("${alarm_system_from_name}")
    private String mailFromName;


    @Value("${spring.mail.username}")
    private String addressFrom;

    @Autowired
    private JavaMailSender mailSender;

    public AmsTxO subMainProc(AmsTxI inObj) {
        log.info("inObj : {}", inObj);
        AmsTxO outObj = new AmsTxO();
        outObj.setTrx_id("AMSTXO");
        outObj.setType_id("O");

        final String mailSubject = inObj.getMail_subject();
        final String mailContent = inObj.getMail_content();
        final List<String> toAddressIarys = inObj.getMail_to_address_iary();
        final List<String> mailAttachementPathIary = inObj.getMail_attachement_path_iary();

        if (toAddressIarys == null) {
            outObj.setRtn_code("0000001");
            outObj.setRtn_message("缺少收件人信息结点[mail_to_address_iary]");
            return outObj;
        }
        final int mailType = inObj.getMail_type();
        if (AmsTxI.MAIL_TYPE_SIMPLE_MESSAGE == mailType) {
            sendSimpleMail(mailSubject, mailContent, toAddressIarys);
        } else if (AmsTxI.MAIL_TYPE_ATTACHEMENT == mailType) {
            if (mailAttachementPathIary == null) {
                outObj.setRtn_code("0000002");
                outObj.setRtn_message("缺少附件的路径位置结点[mail_attachement_path_iary]");
                return outObj;
            }
            sendAttechmentProc(mailSubject, mailContent, toAddressIarys, mailAttachementPathIary);
        } else {
            log.error("error mail type : {}", mailType);
        }

        outObj.setRtn_code("0000000");
        outObj.setRtn_message("success");
        return outObj;
    }

    /**
     * 发送简单邮件
     *
     * @return
     */
    public void sendSimpleMail(String mailSubject, String mailContent, List<String> toAddressIarys) {
        if (toAddressIarys != null) {
            toAddressIarys.forEach((toAdress) -> {
                SimpleMailMessage message = new SimpleMailMessage();
                message.setFrom(mailFromName);
                message.setTo(toAdress);
                message.setSubject(mailSubject);
                message.setText(mailContent);
                mailSender.send(message);
            });
        }
    }


    private void sendAttechmentProc(String subject, String text, List<String> toAddresses, final List<String> filePaths) {

        toAddresses.forEach(to -> {

            try {
                MimeMessage mimeMessage = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
                helper.setFrom(mailFromName);

                helper.setTo(to);
                helper.setSubject(subject);
                helper.setText(text);

                filePaths.forEach(filePath -> {
                    FileSystemResource file = new FileSystemResource(new File(filePath));
                    try {
                        helper.addAttachment(file.getFilename(), file);
                    } catch (MessagingException e) {
                        throw new RuntimeException(e);
                    }
                });


                mailSender.send(mimeMessage);
            } catch (MessagingException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        });

    }
}
